from flask import current_app, jsonify
from flask import g
from flask import session

from info.utitls.response_code import RET
import functools

def set_rank_class(index):

    if index == 1:
        return "first"
    elif index == 2:
        return "second"
    elif index == 3:
        return "third"
    else:
        return ""

# 使用@functools.wraps（func）解决使用装饰器装饰视图函数会使函数名称或注释发生一些改变

# 传入参数是视图函数名称
#  装饰器装饰视图函数
def user_login_data(view_func):
    @functools.wraps(view_func)
    def wrapper(*args, **kwargs):

        # g能够临时保存本次请求的内容
        # 实现需要装饰的内容逻辑
        user_id = session.get("user_id")
        print(user_id)
        # 根据user——id查询用户对象
        # 延迟导入
        from info.models import User
        user = None
        if user_id:
            try:
                user = User.query.get(user_id)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")
        # 借助g对象临时保存user
        g.user = user
        # 原有函数的逻辑
        result = view_func(*args, **kwargs)
        return result


    return wrapper